package edu.scau.web.system;

import edu.scau.core.constants.AjaxResult;
import edu.scau.core.constants.HttpStatus;
import edu.scau.core.util.ServletUtils;
import edu.scau.system.domain.LoginUser;
import edu.scau.system.domain.User;
import edu.scau.system.service.IUserAuthService;
import edu.scau.system.service.IUserService;
import edu.scau.system.service.TokenService;
import edu.scau.system.vo.LoginUserVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
//@RequestMapping("/auth")
@Tag(name = "用户登录/退出",description = "")
public class UserAuthController {
    @Autowired
    private IUserAuthService userAuthService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IUserService userService;
    @Operation(summary = "登录",description = "用户登录",
            requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(
                    description = "登录表单信息",
                    required = true,
                    content = @Content(
                            mediaType = "application/json",
                            schema = @Schema(implementation = LoginUserVo.class)
                    )
    )
    )
    @PostMapping("auth/login")
    public AjaxResult login(@RequestBody LoginUserVo loginUserVo){
        Map<String, Object> data = new HashMap<>();
        String token = userAuthService.login(loginUserVo.getUsername(),loginUserVo.getPassword());
        data.put("token", token);
        return AjaxResult.success("登录成功",data);
    }

    @Operation(summary = "退出登录",description = "退出登录")
    @GetMapping("/logout")
    public void logout(){}

    @Operation(summary = "获取当前登录用户信息",description = "获取当前登录用户信息")
    @GetMapping("/getInfo")
    public AjaxResult getInfo() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        if(loginUser == null){
            //未携带token
            return AjaxResult.error(HttpStatus.FORBIDDEN,"认证过期");
        }
        User user = loginUser.getUser();
        Map<String, Object> data = new HashMap<>();
        data.put("name",user.getUserName());
        data.put("avatar",user.getAvatar());
        data.put("roles", userService.selectUserRoleGroup(user));
        return AjaxResult.success(data);
    }

}
